# -*- encoding=utf8 -*-

__author__ = "code哥"
import random
import sys
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

dev = False

if dev:
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
    from airtest.cli.parser import cli_setup

    if not cli_setup():
        auto_setup(__file__, logdir=None, devices=[
            "Android://127.0.0.1:5037/M960BDPT226TA?cap_method=JAVACAP&&ori_method=ADBORI",
        ])
else:
    import timeout_decorator

    # M960BDPT226TA WIFI 10.0.0.26 48003
    argv1 = str(sys.argv[1])
    argv2 = str(sys.argv[2])
    argv3 = str(sys.argv[3])
    argv4 = str(sys.argv[4])

    if argv2 == 'USB':
        conn_info = 'Android://127.0.0.1:5037/{uuid}?cap_method=JAVACAP&&ori_method=ADBORI'.format(
            uuid=argv1)
        device = connect_device(conn_info)
    else:
        # WIFI模式
        conn_info = 'Android://127.0.0.1:5037/{clientIp}:{port}'.format(
            clientIp=argv3,
            port=argv4)
        print(conn_info)
        device = connect_device(conn_info)

    poco = AndroidUiautomationPoco(device, use_airtest_input=True, screenshot_each_action=False)

    logdir = "{path}/static/source_img/{fileName}/{devices}".format(
        path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        fileName=str(os.path.abspath(__file__).split('/')[-1]).split('.py')[0],
        devices=argv1)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    auto_setup(__file__,
               logdir=logdir,
               devices=[conn_info, ],
               project_root="{root}".format(root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


def start():
    if not dev:
        set_logdir(logdir)
        # set_current(str(sys.argv[1]))
    # 退到桌面
    home()
    stop_app('cn.weli.story')
    sleep(1)
    start_app('cn.weli.story')
    start_home()


def start_home():
    sleep(15)
    recycler_view = poco("cn.weli.story:id/recyclerView")
    # recycler_view.wait_for_appearance()
    recycler_view.swipe([0, 0.5])
    sleep(2)
    if recycler_view.exists():
        ll_list = recycler_view.children()
        if len(ll_list) > 0:
            for item in ll_list:
                id_layout = item.offspring("cn.weli.story:id/layout")
                if id_layout.exists():
                    item.click()
                    break
    while True:
        loop_body()


@timeout_decorator.timeout(120)
def loop_body():
    print('loop_body......')
    # sleep(2 + random.randint(0, 2))
    sleep(1)
    poco("cn.weli.story:id/scrollview").swipe([0, -0.9], duration=1.5)
    sleep(1)

    relativeLayout = poco("android.widget.FrameLayout").offspring("android:id/content").offspring(
        "android.widget.RelativeLayout")
    if relativeLayout.exists():
        relativeLayout.offspring("cn.weli.story:id/bt_ok")[1].click()

    ll_chat_guide = poco("android:id/content").offspring("cn.weli.story:id/ll_chat_guide")
    if ll_chat_guide.exists():
        ll_chat_guide.child("android.widget.ImageView").click()

    tv_height_more = poco("cn.weli.story:id/tv_height_more")
    if tv_height_more.exists():
        tv_height_more.click()

    # tab
    tv_news = poco(type="android.widget.TextView", name="cn.weli.story:id/tv_news")
    if tv_news.exists():
        tv_news.click()

    ll_chat_room_tag_list = poco(name="cn.weli.story:id/ll_chat_room_tag")
    if ll_chat_room_tag_list.exists() and len(ll_chat_room_tag_list) > 0:
        for item in ll_chat_room_tag_list:
            item.click()
            break

    rl_list = poco(type="android.widget.RelativeLayout", name="cn.weli.story:id/layout")
    if rl_list.exists() and len(rl_list) > 0:
        for item in rl_list:
            item.click()
            break


def main():
    try:
        start()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()
